package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.annotation.Incomplete;
import org.aeon.entity.ChatGroup;
import org.aeon.entity.dto.GroupInfoDto;
import org.aeon.message.request.GroupCreateRequestMessage;
import org.aeon.message.response.GroupCreateResponseMessage;
import org.aeon.service.ChatGroupService;
import org.aeon.service.UserGroupRelationService;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.UserGroupRelationServiceFactory;

import java.util.Set;

/**
 * @author: MissingAeon
 * @date: 2024/2/19 0:45
 * @description: 创建聊天组请求处理
 */
@Slf4j
@ChannelHandler.Sharable
@Incomplete
public class GroupCreateRequestHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        final GroupCreateResponseMessage resMsg = new GroupCreateResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final String groupName = msg.getGroupName();
        // 判断组名重复
        final ChatGroupService chatGroupService = ChatGroupServiceFactory.getService();
        final boolean chatGroupExist = chatGroupService.isChatGroupExist(groupName);
        if (chatGroupExist) {
            // 重复
            resMsg.setResponse(false, "重复的群聊名称");
            ctx.writeAndFlush(resMsg);
            return;
        }
        // 创建群聊
        final Long userId = msg.getUserId();
        final ChatGroup chatGroup = chatGroupService.insertChatGroup(groupName, userId);
        if (chatGroup == null) {
            resMsg.setResponse(false, "群聊创建失败");
            ctx.writeAndFlush(resMsg);
            return;
        }
        // 添加组员
        final UserGroupRelationService groupRelationService = UserGroupRelationServiceFactory.getService();
        final Set<Long> members = msg.getMembers();
        final int i = groupRelationService.fillGroup(chatGroup.getId(), userId, members);
        if (i != -1) {
            resMsg.setResponse(true, "创建组成功，成功添加了" + i + "名用户");
            final GroupInfoDto groupInfo = ChatGroupServiceFactory.getService().getChatGroupInfo(chatGroup.getId());
            resMsg.setMessage(groupInfo);
            ctx.writeAndFlush(resMsg);
            log.debug("{}创建了群聊：{}", userId, groupName);
        } else {
            resMsg.setResponse(false, "群成员添加失败");
            ctx.writeAndFlush(resMsg);
        }
    }
}
